package org.example.service.middlegateway.interceptor;

import com.alibaba.fastjson.JSONObject;
import org.example.service.middlegateway.common.constant.ResponseCodeConst;
import org.example.service.middlegateway.common.domain.dto.ResponseDTO;
import org.example.service.middlegateway.feign.AuthFeignClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 认证权限拦截器拦截器
 */
@Component
public class AuthInterceptor extends HandlerInterceptorAdapter {
    @Autowired
    AuthFeignClient authFeignClient;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        this.crossDomainConfig(response);
        String token = request.getHeader("Authorization");
        if (token == null) {
            this.outputResult(response, ResponseCodeConst.AUTH_ERROR);
            return false;
        }

        Boolean hasAuth = authFeignClient.hasAuth(token);
        if (!hasAuth) {
            this.outputResult(response, ResponseCodeConst.AUTH_ERROR);
            return false;
        }
        return true;
    }

    /**
     * 配置跨域
     *
     * @param response
     */
    private void crossDomainConfig(HttpServletResponse response) {
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Credentials", "true");
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, PUT, OPTIONS, DELETE, PATCH");
        response.setHeader("Access-Control-Expose-Headers", "*");
        response.setHeader("Access-Control-Allow-Headers", "Authentication,Origin, X-Requested-With, Content-Type, " + "Accept, x-access-token");
        response.setHeader("Cache-Control", "no-cache");
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Expires ", "-1");
    }

    /**
     * 错误输出
     *
     * @param response
     * @param responseCodeConst
     * @throws IOException
     */
    private void outputResult(HttpServletResponse response, ResponseCodeConst responseCodeConst) throws IOException {
        ResponseDTO<Object> wrap = ResponseDTO.wrap(responseCodeConst);
        String msg = JSONObject.toJSONString(wrap);
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().write(msg);
        response.flushBuffer();
    }
}
